﻿using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace PhysicalExamination5.WebApi.Utility.JWT
{
    public class CustomHSJWTService : ICustomJWTService
    {
        #region Option注入
        private readonly JWTTokenOptions _JWTTokenOptions;

        public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
        }

        #endregion
        /// <summary>
        /// funHuoQuToKen 获取ToKen
        /// </summary>
        /// <param name="strDengLuXiTong"></param>
        /// <param name="strJueSeId"></param>
        /// <param name="strUserId"></param>
        /// <param name="strUserName"></param>
        /// <param name="strYuanQuQianZhui"></param>
        /// <param name="strYuanQu"></param>
        /// <param name="intYouXiaoTime"></param>
        /// <returns></returns>
        public string funHuoQuToKen(string strDengLuXiTong, string strJueSeId, string strUserId, string strUserName, string strYuanQuQianZhui,string strYuanQu, int intYouXiaoTime)
        {
            //获取时间戳
            var expiresTime = DateTime.UtcNow.AddMinutes(intYouXiaoTime);

            //准备有效载荷
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim("DengLuXiTong", strDengLuXiTong));
            claims.Add(new Claim("JueSeId", strJueSeId));
            claims.Add(new Claim("UserId", strUserId));
            claims.Add(new Claim("UserName", strUserName));
            claims.Add(new Claim("YuanQuQianZhui", strYuanQuQianZhui));
            claims.Add(new Claim("YuanQu", strYuanQu));
            //准备加密key
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));
            //Sha256 加密方式
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                  issuer: _JWTTokenOptions.Issuer,
                  audience: _JWTTokenOptions.Audience,
                  expires: expiresTime,
                  claims: claims,
                  signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
